package com.vic.framework.helper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *数据库操作助手类
 * @author VIC
 *
 */
public final class DatabaseHrelper {
	
	private static final Logger logger = LoggerFactory.getLogger(DatabaseHrelper.class);

	private static ThreadLocal<Connection> connContainer = new ThreadLocal<Connection>();
	/**
	 * 开启事务
	 */
	public static void beginTransaction(){
		Connection conn = getConnection();
		if(conn != null) {
			try {
				conn.setAutoCommit(false);
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				connContainer.set(conn);
			}
		}
	}
	
	/**
	 * 提交事务
	 */
	public static void commitTransaction(){
		Connection conn = connContainer.get();
		try{
			if(conn != null) {
				conn.commit();
				conn.close();
			}
		}catch(Exception e){
			logger.error("commoit transaction failure", e);
		}finally {
			connContainer.remove();
		}
		
	}
	
	/**
	 * 回滚事务
	 */
	public static void rollbackTransaction(){
		Connection conn = connContainer.get();
		try{
			if(conn != null) {
				conn.rollback();
				conn.close();
			}
		}catch(Exception e){
			logger.error("rollback transaction failure", e);
		}finally {
			connContainer.remove();
		}
	}
	
	
	
	
	/**
	 * 获取链接
	 */
	public static Connection getConnection(){
		Connection conn = connContainer.get();
		try{
			if(conn == null) {
				Class.forName(driver);
				conn = DriverManager.getConnection(url, username, password);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			connContainer.set(conn);
		}
		return conn;
	}
	
	/**
	 * 关闭连接
	 */
	public static void closeConnection(){
		Connection conn = connContainer.get();
		try{
			if(conn != null) {
				conn.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			connContainer.remove();
		}
	}
	
	
	private static final String driver = "com.mysql.jdbc.Driver";
	
	private static final String url = "jdbc:mysql://lcoalhost:3306/test";
	
	private static final String username = "root";
	
	private static final String password = "123456";
	
}
